/*对话消息列表组件 */
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { List, Badge } from 'antd-mobile'
const Item = List.Item 
const Brief = Item.Brief

/**
 * 对chatMsg，并且每个组的lastMsg组成的数组
 * 1. 找出每个聊天的last_id，并且分到每个lastMsg组成的数组
 * 2. 得到所有lastMsg的数组
 * 3. 对数组进行排序(create_time降序)
 */
function getLastMsgs(chatMsgs, userid){
  //  * 1. 找出每个聊天的last_id，并且分到每个lastMsg组成的数组
  const lastMsgObjs = {}
  chatMsgs.forEach(msg => {

    // 对每一个msg进行统计, 如果消息是发给我的并且msg是未读的
    if (msg.to === userid && !msg.read) {
      msg.unReadCount = 1
    }else{
      msg.unReadCount = 0
    }

    const chatId = msg.chat_id
    let lastMsg = lastMsgObjs[chatId]   // "chat_id": { content: 'xxx', chat_id: '...', ... }
    if (!lastMsg) { // 没有
      // 当前msg就是所在组的msg
      lastMsgObjs[chatId] = msg
    }else{  //有
      // 如果msg比lastmsg晚，将msg保存为lastmsg
      const unReadCount = lastMsg.unReadCount + msg.unReadCount
      if (msg.create_time>lastMsg.create_time) {
        lastMsgObjs[chatId] = msg
      }
      lastMsgObjs[chatId].unReadCount = unReadCount
    }
  });
  //  * 2. 得到所有lastMsg的数组
  const lastMsgs = Object.values(lastMsgObjs)
  //  * 3. 对数组进行排序(create_time降序)
  lastMsgs.sort((m1, m2) => {
    return m2.create_time-m1.create_time
  })
  return lastMsgs
}

class Message extends Component {
  render() {
    const {user} = this.props
    const {users, chatMsgs} = this.props.chat
    const lastMsgs = getLastMsgs(chatMsgs, user._id)
    
    // 对chatMsgs进行分组
    return (
      <List>
        { 
          lastMsgs.map(msg => 
            {
              // 得到目标用户的id
              const targetId = msg.to === user._id ? [msg.from] : [msg.to]
              // 得到目标用户的信息
              const targetInfo = users[targetId]
              return (
                <Item key={msg.create_time}
                  onClick={() => this.props.history.push(`/chat/${targetId}`)}
                  extra={<Badge text={msg.unReadCount} />}
                  thumb={targetInfo.header ? require(`../../assets/headers/${targetInfo.header}.png`) : null}
                  arrow='horizontal' >
                  {msg.content}
                <Brief>{targetInfo.username}</Brief>
                </Item>
              )
            }
          )
          
        }
      </List>
    )
  }
}
export default connect(
  state => ({user: state.user, chat: state.chat}),
  {}
)(Message)